import React, { Component } from "react";
import { stubDetail, erpUserList, saveWorkOrder } from "../../../fetch/fetchApi";
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete, Radio, Spin, Modal, message } from 'antd';
import AreaOptions from '../../../components/dataEntry/areaOptions';
import FaultCodeList from './faultCodeList';

const FormItem = Form.Item;
const Option = Select.Option;
const AutoCompleteOption = AutoComplete.Option;
const RadioGroup = Radio.Group;
const {TextArea} = Input;

const defaultFormData = {
    id: "0",
    group: "2",
    stubProtity: "1",
    stubType: "0",
    stubFloor: "0"
}
class AddWorkOrder extends Component {

    constructor(props) {
        super(props);
        this.init();
        this.state = {
            workOrder: {
                stubProtity: defaultFormData.stubProtity,
                stubType: defaultFormData.stubType,
                stubFloor: defaultFormData.stubFloor
            },
            mountAddrRadioChecked: true,
            mountSpin: false,
            faultModalVisible: false,
            failInfoDisplay: 'none',
            shareInfoDisplay: 'none'
        };
    }

    init() {
        this.cityOptions = AreaOptions();
        this.getAllCs();
        this.initParams();
    }

    initParams() {
        this.formData = JSON.parse(JSON.stringify(defaultFormData));
        this.mountCityInfo = {};
        this.shareCityInfo = {};
        this.selectedAddrRadio = "1";
    }

    getAllCs() {
        erpUserList({
            role: "1953"
        }).then((res) => {
            console.log(res);
            if (!res) {
                return;
            }
            if (res.data.code === "200") {
                let csOptions = [];
                const currentUserName = res.data.data.currentUserName;
                const list = res.data.data.list;
                let csId = "-1";
                for ( let item of list ) {
                    if (currentUserName === item.name) {
                        csId = item.id;
                    }
                    csOptions.push(<Option value={item.id} key={item.id}>{item.name}</Option>);
                }
                let workOrder = this.state.workOrder;
                if (csId === "-1") {
                    this.setState({
                        failInfoDisplay: ''
                    })
                }
                workOrder.csId = csId;
                this.formData.csId = csId;
                this.setState({
                    csOptions: csOptions,
                    workOrder: workOrder
                })
            }

        })
    }

    handleGetBtnClick = () => {
        if (!this.formData.stubId) {
            message.error("请输入桩id");
            return;
        }
        this.setState({
            mountSpin: true
        })
        stubDetail({
            stubId: this.formData.stubId,
            flag: this.formData.stubProtity === "1" ? 1 : null
        }).then((res) => {
            if (!res) {
                return;
            }
            if (res.data.code === "200") {
                const resData = res.data.data;
                let workOrder = this.state.workOrder;
                if (resData) {
                    // 安装信息
                    //区
                    const mountDistrict = resData.mountDistrict;
                    const mountAddr = resData.mountAddr;
                    let mountCityArr = [];
                    if (mountDistrict) {
                        const pCode = mountDistrict.substring(0, 2);
                        const cCode = mountDistrict.substring(0, 4);
                        mountCityArr.push(pCode);
                        mountCityArr.push(cCode);
                        mountCityArr.push(mountDistrict);
                        this.mountCityInfo.province = resData.mountProvince;
                        this.mountCityInfo.city = resData.mountCity;
                        this.mountCityInfo.district = resData.mountDistrict;
                    }
                    workOrder.mountCity = mountCityArr;
                    workOrder.mountAddr = mountAddr;
                    this.mountCityInfo.addrDetail = resData.mountAddr;

                    // 共享信息
                    if (this.formData.stubProtity !== "1") {
                        const stubType = resData.stubType;
                        const shareCity = resData.shareCity;
                        const shareAddr = resData.shareAddr;
                        if (stubType) {
                            workOrder.stubType = stubType;
                        }
                        let shareCityArr = [];
                        if (shareCity) {
                            const pCode = shareCity.substring(0, 2);
                            const cCode = shareCity.substring(0, 4);
                            shareCityArr.push(pCode);
                            shareCityArr.push(cCode);
                            shareCityArr.push(shareCity);
                            this.shareCityInfo.province = pCode + "0000";
                            this.shareCityInfo.city = cCode + "00";
                            this.shareCityInfo.district = shareCity;
                        }
                        workOrder.shareCity = shareCityArr;
                        workOrder.shareAddr = shareAddr;
                        this.shareCityInfo.addrDetail = shareAddr;
                    }
                } else {
                    workOrder.mountAddr = "";
                    workOrder.mountCity = "";
                    workOrder.shareCity = "";
                    workOrder.shareAddr = "";
                }
                console.log(workOrder);
                this.setState({
                    workOrder: workOrder
                })
            }
            this.setState({
                mountSpin: false
            })
        })
    }

    handleFaultInputClick = () => {
        this.setState({
            faultModalVisible: true
        })
    }

    handleFaultModalCancelClick = () => {
        this.setState({
            faultModalVisible: false
        })
    }

    handleAddrRadioClick=(e) => {
        this.selectedAddrRadio = e.target.value;
        if (e.target.value === "1") {
            this.setState({
                mountAddrRadioChecked: true,
                shareAddrRadioChecked: false
            })
        } else {
            this.setState({
                mountAddrRadioChecked: false,
                shareAddrRadioChecked: true
            })
        }
    }

    handleClearBtnClick=(e) => {
        this.setState({
            workOrder: {
                csId: "-1",
                stubType: defaultFormData.stubType,
                stubProtity: defaultFormData.stubProtity,
                stubFloor: defaultFormData.stubFloor,
            },
            faultValue: "",
            mountAddrRadioChecked: true,
            shareAddrRadioChecked: false
        })
        this.initParams();
    }

    handleMountCityChange=(e) => {
        console.log(e);
        this.mountCityInfo.province = e[0] + "0000";
        this.mountCityInfo.city = e[1] + "00";
        this.mountCityInfo.district = e[2];

        let workOrder = this.state.workOrder;
        workOrder.mountCity = e;
        this.setState({
            workOrder: workOrder
        })
    }

    handleShareCityChange=(e) => {
        console.log(e);
        this.shareCityInfo.province = e[0] + "0000";
        this.shareCityInfo.city = e[1] + "00";
        this.shareCityInfo.district = e[2];

        let workOrder = this.state.workOrder;
        workOrder.shareCity = e;
        this.setState({
            workOrder: workOrder
        })
    }

    handleMountAddrInputChange=(e) => {
        let workOrder = this.state.workOrder;
        workOrder.mountAddr = e.target.value;
        this.mountCityInfo.addrDetail = e.target.value;
        this.setState({
            workOrder: workOrder
        })
    }

    handleShareAddrInputChange=(e) => {
        let workOrder = this.state.workOrder;
        workOrder.shareAddr = e.target.value;
        this.shareCityInfo.addrDetail = e.target.value;
        this.setState({
            workOrder: workOrder
        })
    }

    handleFaultCodeList=(params) => {
        console.log(params);
        this.formData.faultCode = params.id;
        this.formData.faultType = params.type;
        this.formData.priority = params.priority;
        this.setState({
            faultValue: params.name,
            faultModalVisible: false
        })
    }

    handleChange=(type, value) => {
        this.formData[type] = value;
        let workOrder = this.state.workOrder;
        workOrder[type] = value;
        this.setState({
            workOrder: workOrder
        })
    }

    handleTextAreaChange=(type, e) => {
        if(e.target.value.length>50){
            message.error("字数50以内！");
            e.preventDefault();
            return;
        }
        this.formData[type] = e.target.value;
        let workOrder = this.state.workOrder;
        workOrder[type] = e.target.value;
        this.setState({
            workOrder: workOrder
        })
    }

    handleSubmit=(e) => {
        e.preventDefault();
        if (this.selectedAddrRadio === "1") {
            this.formData.province = this.mountCityInfo.province;
            this.formData.city = this.mountCityInfo.city;
            this.formData.district = this.mountCityInfo.district;
            this.formData.addrDetail = this.mountCityInfo.addrDetail;
        } else {
            this.formData.province = this.shareCityInfo.province;
            this.formData.city = this.shareCityInfo.city;
            this.formData.district = this.shareCityInfo.district;
            this.formData.addrDetail = this.shareCityInfo.addrDetail;
        }
        const formData = this.formData;
        console.log(formData);
        if (!formData.faultType || !formData.faultDesc || !formData.vehicleModel || !formData.repairPerson || !formData.phone ||
                !formData.stubId || !formData.province || !formData.city || !formData.district
                || !formData.addrDetail) {
            message.error("请完善表单信息！")
            return;
        }
        if (!formData.csId || formData.csId === "-1") {
            message.error("请选择客服！")
            return;
        }
        this.setState({
            saveBtnLoading: true
        })
        saveWorkOrder(this.formData).then((res) => {
            if (!res) {
                return;
            }
            if (res.data.code === "200") {
                message.success("保存成功");
                this.handleClearBtnClick();
            }
            this.setState({
                saveBtnLoading: false
            })
        })
    }

    handleStubProtityRadioChange=(e) => {
        let workOrder = this.state.workOrder;
        workOrder.stubProtity = e.target.value;
        if (e.target.value === "1") {
            this.setState({
                shareInfoDisplay: 'none',
                workOrder: workOrder
            })
        } else {
            this.setState({
                shareInfoDisplay: '',
                workOrder: workOrder
            })
        }
        this.formData.stubProtity = e.target.value;
    }

    render() {
        const formItemLayout = {
            gutter: 8,
            labelCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 2
                },
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 8,
                    offset: 1
                },
            },
        };
        const mutiEleFormItemLayout = JSON.parse(JSON.stringify(formItemLayout));
        mutiEleFormItemLayout.wrapperCol.sm.span = 12;
        return (
            <Form onSubmit={this.handleSubmit}>
                <FormItem {...formItemLayout} label="电桩分类：">
                    <RadioGroup onChange={this.handleStubProtityRadioChange} value={this.state.workOrder.stubProtity} defaultValue={defaultFormData.stubProtity}>
                        <Radio value="1">公桩</Radio>
                        <Radio value="0">私桩</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem {...mutiEleFormItemLayout} label="电桩编号：">
                    <Row gutter={8}>
                        <Col span={16}>
                            <Input placeholder="请输入电桩编号" onChange={(e) => this.handleChange("stubId", e.target.value)} value={this.state.workOrder.stubId}/>
                        </Col>
                        <Col span={8}>
                            <Button onClick={this.handleGetBtnClick}>获取</Button>
                        </Col>
                    </Row>
                </FormItem>
                <FormItem {...formItemLayout} label="电桩类型：">
                    <RadioGroup onChange={(e) => this.handleChange("stubType", e.target.value)} value={this.state.workOrder.stubType} defaultValue={defaultFormData.stubType}>
                        <Radio value="1">直流</Radio>
                        <Radio value="0">交流</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem {...formItemLayout} label="安装位置：">
                    <RadioGroup onChange={(e) => this.handleChange("stubFloor", e.target.value)} value={this.state.workOrder.stubFloor} defaultValue={defaultFormData.stubFloor}>
                        <Radio value="0">地上</Radio>
                        <Radio value="1">地下</Radio>
                    </RadioGroup>
                </FormItem>
                <Spin spinning={this.state.mountSpin} style={{
                'width': 900
            }}>
                    <FormItem {...formItemLayout} label="安装城市：">
                        <Cascader options={this.cityOptions} placeholder="请选择城市" value={this.state.workOrder.mountCity} onChange={this.handleMountCityChange} />
                    </FormItem>
                    <FormItem {...mutiEleFormItemLayout} label="安装地址：">
                        <Row gutter={8}>
                            <Col span={16}>
                                <Input onChange={this.handleMountAddrInputChange} value={this.state.workOrder.mountAddr}/>
                            </Col>
                            <Col span={8}>
                                <Radio value={1} checked={this.state.mountAddrRadioChecked} onClick={this.handleAddrRadioClick}></Radio>
                            </Col>
                        </Row>
                    </FormItem>
                
                    <FormItem style={{
                'display': this.state.shareInfoDisplay
            }} {...formItemLayout} label="共享城市：">
                        <Cascader options={this.cityOptions} placeholder="请选择城市" value={this.state.workOrder.shareCity} onChange={this.handleShareCityChange} />
                    </FormItem>
                    <FormItem style={{
                'display': this.state.shareInfoDisplay
            }} {...mutiEleFormItemLayout} label="共享地址：">
                        <Row gutter={8}>
                            <Col span={16}>
                                <Input onChange={this.handleShareAddrInputChange} value={this.state.workOrder.shareAddr}/>
                            </Col>
                            <Col span={8}>
                                <Radio value={2} checked={this.state.shareAddrRadioChecked} onClick={this.handleAddrRadioClick}></Radio>
                            </Col>
                        </Row>
                    </FormItem>
                </Spin>
                <FormItem {...formItemLayout} label="故障代码：">
                    <Input style={{
                'cursor': 'pointer'
            }} readOnly="readonly" value={this.state.faultValue} onClick={this.handleFaultInputClick}/>
                </FormItem>
                <FormItem {...formItemLayout} label="故障描述：">
                    <TextArea onChange={(e) => this.handleTextAreaChange("faultDesc", e)} value={this.state.workOrder.faultDesc}/>
                </FormItem>
                <FormItem {...formItemLayout} label="车    型：">
                    <Input onChange={(e) => this.handleChange("vehicleModel", e.target.value)} value={this.state.workOrder.vehicleModel} />
                </FormItem>
                <FormItem {...formItemLayout} label="报 修 人：">
                    <Input onChange={(e) => this.handleChange("repairPerson", e.target.value)} value={this.state.workOrder.repairPerson} />
                </FormItem>
                <FormItem {...formItemLayout} label="联系电话：">
                    <Input onChange={(e) => this.handleChange("phone", e.target.value)} value={this.state.workOrder.phone} />
                </FormItem>
                <FormItem {...formItemLayout} label="备注信息：">
                    <TextArea onChange={(e) => this.handleTextAreaChange("remark", e)} value={this.state.workOrder.remark} />
                </FormItem>
                <FormItem {...formItemLayout} label="客服人员：">
                    <Row>
                        <Col span={8}>
                            <Select onChange={(e) => this.handleChange("csId", e)} defaultValue="-1" value={this.state.workOrder.csId}>
                                <Option value="-1">请选择</Option>
                                {this.state.csOptions}
                            </Select>
                        </Col>
                        <Col span={8} offset={2} style={{
                'display': this.state.failInfoDisplay
            }}>
                            <span style={{
                'color': 'red'
            }}>(信息关联失败，请手动选择)</span>
                        </Col>
                    </Row>
                </FormItem>
                <FormItem {...formItemLayout}>
                    <Row>
                        <Col span={4}>
                            <Button loading={this.state.saveBtnLoading} type="primary" htmlType="submit">保存</Button>
                        </Col>
                        <Col span={4}>
                            <Button onClick={this.handleClearBtnClick}>清空</Button>
                        </Col>
                    </Row>
                </FormItem>
                <Modal width="1000px" footer={null} visible={this.state.faultModalVisible} onCancel={this.handleFaultModalCancelClick}>
                    <FaultCodeList handle={this.handleFaultCodeList}/>
                </Modal>
            </Form>
        )
    }
}

export default AddWorkOrder;